<template>
    <a-form ref='formRef' :label-col='{span : 5}' :model='formData'>
        <a-form-item label='设置范围' name='range' :rules="[{required : true, message : '请选择设置范围'}]">
                <a-select show-search v-model:value='formData.range' :options='rangeOptions'></a-select>
        </a-form-item>
        <a-form-item v-if="formData.range == 1" label='选择设备' name='deviceIds' :rules="[{required : true, message : '请选择设备'}]">
            <div :class="$style.selectDevice">
                <a-select :placeholder="formData.deviceIds.length == 0 ? '请选择设备' : `已选择${formData.deviceIds.length}台设备`"></a-select>
                <div :class="$style.mask" @click="openSelectDevice"></div>
            </div>
        </a-form-item>
    </a-form>

    <a-drawer v-model:open='visible' title='选择设备' width='1000px' placement="right" :confirm='confirmSelectDevice'>
        <SelectDevice :device-type-id="row.deviceTypeId" ref="selectDeviceRef" />
        <template #footer>
            <a-space>
                <a-button @click="closeSelectDevice">取消</a-button>
                <a-button type="primary" @click="confirmSelectDevice">确定</a-button>
            </a-space>
        </template>
    </a-drawer>
</template>



<script lang="ts" setup>
    import SelectDevice from './SelectDevice.vue'
    import { ref } from 'vue';
import { setDeviceParamsApi } from '@/api/devices/Device';
    

    const props = defineProps<{
        row? : any;
    }>()

    const visible = ref(false)


    const selectDeviceRef = ref()

    function openSelectDevice() {
        visible.value = true
    }

    function closeSelectDevice(){
        visible.value = false
    }

    function confirmSelectDevice() {
        formData.value.deviceIds = selectDeviceRef.value.select()
        formRef.value.validateFields(['deviceIds'])
        closeSelectDevice()
    }

    const formRef = ref()
    
    

    const rangeOptions = ref([{label : '指定设备', value : 1}, {label : '当前设备类型', value : 2}, {label : '当前设备类型及全部子类型', value : 3}])
    
    const formData = ref({
        range : '',
        deviceIds:[]
    })
    

    if(props.row) {
        for(let k in props.row) {
            if(k in formData.value) {
                formData.value[k] = props.row[k]
            }
        }
    }

    async function submit() {
        let params  = await formRef.value.validate()
        if(params.range != 1) {
            delete params.deviceIds
        }

        params.id = props.row.id


        return setDeviceParamsApi(params)
    }

    defineExpose({
        submit
    })

</script>

<style lang="scss" module>
    .selectDevice{
        position: relative;
        .mask{
            position: absolute;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            z-index: 3;
            text-align: center;
            display: flex;
            align-items: center;
        }
    }
</style>